<template>
  <div class="page-controller">
    <FIPanel class="page-tree" :usePadding="false">
      <div class="page-tree__title">前端应用模块列表</div>
      <div class="page-tree__line"></div>
      <el-input
        class="page-tree__search"
        v-model="filterText"
        :prefix-icon="Search"
        style="width: 250px"
        placeholder="请输入"
      />
      <el-tree
        ref="treeRef"
        style="max-width: 600px"
        :data="state.treeData"
        :props="defaultProps"
        :highlight-current="true"
        @node-click="handleNodeClick"
        lazy
        :load="loadNode"
        :filter-node-method="filterNode"
        @current-change="onCurrentNodeChange"
      >
        <template #default="{ node }">
          <div
            class="custom-tree-node"
            :class="[{ 'custom-tree-node3': node.level === 3 }, { 'custom-tree-node4': node.level === 4 }]"
          >
          <el-tooltip
            class="box-item"
            effect="dark"
            :content="node.label"
            placement="top-start"
          >
            <span class="custom-tree-node-label common-text-ellipsis"> {{ node.label }}</span>
          </el-tooltip>
            <el-dropdown
              v-if="selectedNode.label === node.label && node.level < 3"
              class="custom-tree-node-add"
              trigger="click"
            >
              <i class="font_family icon-xinzeng"></i>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item v-if="node.level < 3" @click="clickAddModule(node.level, node)"
                    >{{ getTextAdd(node.level) }}
                  </el-dropdown-item>
                  <el-dropdown-item v-if="node.level < 3 && node.level != 1" @click="clickModifyModule(node.level)">{{
                    getTextModify(node.level)
                  }}</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template></el-tree
      >
    </FIPanel>
    <InfoForm
      class="page-form"
      v-model:type="infoFormType"
      :level="infoFormLevel"
      :node-info="selectedNode"
      @handle-save="handleSave"
      @handle-delete="handleDelete"
    ></InfoForm>
    <FIModel v-model="isVisible" title="添加一级模块" width="600px" draggable @confirm="submitForm(ruleFormRef1)">
      <el-form ref="ruleFormRef1" :model="ruleForm1" :rules="rules1" label-width="auto">
        <el-form-item label="一级模块编码" prop="moduleEname1">
          <FISelect v-model="ruleForm1.moduleEname1" :options="optionsArr" multiple></FISelect>
        </el-form-item>
      </el-form>
    </FIModel>
  </div>
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref, watch } from 'vue'
import FIPanel from '@/components/FIPanel.vue'
import FIModel from '@/components/FIModel.vue'
import FISelect from '@/components/FISelect/index.vue'
import { apiRequestPost } from '@/api/globalApi.js'
import { ElTree } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import InfoForm from './infoForm.vue'
import { useMessage } from '@/hooks/message'

const state = reactive({
  treeData: [],
})
interface Tree {
  appCname: string
  leaf?: boolean
  loading?: boolean // 添加此行
}

const filterText = ref('')
const treeRef = ref<InstanceType<typeof ElTree>>()
const isVisible = ref(false)
const ruleFormRef1 = ref(null)
const optionsArr = ref([])
const selNode = ref([])
const handleNodeClick = (data: Tree) => {
  selNode.value = data
  console.log(data, 'data')
}
const ruleForm1 = ref({
  moduleEname1: [],
})
const rules1 = reactive({
  moduleEname1: [{ required: true, message: '请选择一级模块', trigger: 'change' }],
})

const submitForm = async (formEl: any) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      const obj = []
      let currentAppEname = selectedNode.value?.appEname
      ruleForm1.value.moduleEname1.forEach((item) => {
        obj.push({
          appEname: currentAppEname,
          moduleEname1: item,
        })
      })
      apiRequestPost('/rm2/frontPrjMaint/insertModule1', obj)
        .then((res) => {
          if (res.data.success) {
            // infoFormType.value = 'info'
            isVisible.value = false
            refreshTreeNode()
            // loadNode()
            // loadNode(selectedNodeObj.value)
          } else {
          }
        })
        .catch((error: any) => {
          // 处理错误
        })
    } else {
    }
  })
}
const defaultProps = {
  children: 'children',
  label: 'label',
  isLeaf: 'leaf',
}

watch(filterText, (val) => {
  treeRef.value!.filter(val)
})
const selectedNode = ref({})
const selectedNodeObj = ref({})

const onCurrentNodeChange = (e, nodeData) => {
  infoFormType.value = 'info'
  selectedNode.value = e
  selectedNodeObj.value = nodeData
  infoFormLevel.value = nodeData.level
}
const filterNode = (value: string, data: Tree) => {
  if (!value) return true
  return data.label.includes(value)
}
const loadNode = async (node: Node, resolve: (data: Tree[]) => void) => {
  if (node.level === 0) {
    return resolve([{ label: '前端应用模块树' }])
  }
  if (node.level === 1) {
    // 获取项目模块
    try {
      apiRequestPost('/rm2/frontPrjMaint/listProject')
        .then((res) => {
          if (res.data.success) {
            Array.isArray(res.data.data) &&
              res.data.data.forEach((item) => {
                // item.label = item.appCname
                item.label = `[${item.appEname}] ${item.appCname}`
                item.leaf = false
                item.children = null
              })
            const loadedNodes = res.data.data.map((item) => ({
              ...item,
              // 若有子节点，则不是叶子节点，不设置isLeaf；若无子节点，则是叶子节点
              isLeaf: false,
              loading: false,
            }))

            resolve(loadedNodes)
            // if (selNode.value) {
            //   treeRef.value?.setCurrentKey(selNode.value.nodeId)
            // }
          } else {
            resolve([])
          }
        })
        .catch((error: any) => {
          // 处理错误
          resolve([])
        })
    } catch (error) {
      resolve([])
    }
  } else if (node.level === 2) {
    // 获取一级级模块
    try {
      apiRequestPost('/rm2/frontPrjMaint/listModule1', { appEname: node.data.appEname || selNode.value.appEname })
        .then((res) => {
          // state.dataList = res.data.data.result
          if (res.data.success) {
            Array.isArray(res.data.data) &&
              res.data.data.forEach((item) => {
                // item.label = item.moduleCname1
                item.label = `[${item.moduleEname1}]${item.moduleCname1}`
                item.leaf = false
                // item.leaf = true
                item.children = null
              })
            const loadedNodes = res.data.data.map((item) => ({
              ...item,
              // 若有子节点，则不是叶子节点，不设置isLeaf；若无子节点，则是叶子节点
              // isLeaf: false,
              isLeaf: true,
              loading: false,
            }))
            resolve(loadedNodes)
          } else {
            resolve([])
          }
        })
        .catch((error: any) => {
          // 处理错误
          resolve([])
        })
    } catch (error) {
      resolve([])
    }
  } else if (node.level === 3) {
    // 获取二级模块
    try {
      apiRequestPost('/rm2/backendPrjMaint/listModule2', { moduleEname1: node.data.moduleEname1 })
        .then((res) => {
          if (res.data.success) {
            Array.isArray(res.data.data) &&
              res.data.data.forEach((item) => {
                // item.label = item.moduleCname2
                item.label = `[${item.moduleEname2}] ${item.moduleCname2}`
                item.leaf = true
                item.children = null
              })
            const loadedNodes = res.data.data.map((item) => ({
              ...item,
              // 若有子节点，则不是叶子节点，不设置isLeaf；若无子节点，则是叶子节点
              isLeaf: true,
              loading: false,
            }))
            resolve(loadedNodes)
          } else {
            resolve([])
          }
        })
        .catch((error: any) => {
          // 处理错误
          resolve([])
        })
    } catch (error) {
      resolve([])
    }
  }
}
const getTreeNodeInfo = () => {
  apiRequestPost('/rm2/frontPrjMaint/listModule1', { appEname: node.data.appEname })
    .then((res) => {
      // state.dataList = res.data.data.result
      if (res.data.success) {
        Array.isArray(res.data.data) &&
          res.data.data.forEach((item) => {
            // item.label = item.moduleCname1
            item.label = `[${item.moduleEname1}] ${item.moduleCname1}`
            item.leaf = false
            // item.leaf = true
            item.children = null
          })
        const loadedNodes = res.data.data.map((item) => ({
          ...item,
          // 若有子节点，则不是叶子节点，不设置isLeaf；若无子节点，则是叶子节点
          // isLeaf: false,
          isLeaf: true,
          loading: false,
        }))
        resolve(loadedNodes)
      } else {
        resolve([])
      }
    })
    .catch((error: any) => {
      // 处理错误
      resolve([])
    })
}
const infoFormTitle = ref('')
const infoFormType = ref('info')
const infoFormLevel = ref(1)
const clickAddModule = (level, node) => {
  if (level == 2) {
    console.log('app_ename----', node)
    // 添加一级模块
    isVisible.value = true
  } else {
    infoFormType.value = 'add'
    infoFormLevel.value = level
    infoFormTitle.value = getTextAdd(level)
  }
}
const getAllModule1Data = () => {
  optionsArr.value = []
  apiRequestPost('/rm2/backendPrjMaint/listAllModule1', {})
    .then((res) => {
      if (res.data.success) {
        Array.isArray(res.data.data) &&
          res.data.data.forEach((item) => {
            // item.label = item.moduleName
            // item.value = item.moduleName
            optionsArr.value.push({
              label: `[${item.moduleEname1}] ${item.moduleCname1}`,
              value: item.moduleEname1,
            })
          })
      }
    })
    .catch((error: any) => {
      // 处理错误
    })
}
const clickModifyModule = (level) => {
  infoFormType.value = 'modify'
  infoFormLevel.value = level
  infoFormTitle.value = getTextAdd(level)
}
const getTextAdd = (level) => {
  let typeStr = '添加'
  switch (level) {
    case 1:
      return typeStr + '项目'
    case 2:
      return typeStr + '一级模块'
    case 3:
      return typeStr + '二级模块'
    default:
      return typeStr + ''
  }
}

const getTextModify = (level) => {
  let typeStr = '编辑'
  switch (level) {
    case 2:
      return typeStr + '项目'
    case 3:
      return typeStr + '一级模块'
    case 4:
      return typeStr + '二级模块'
    default:
      return ''
  }
}

// type: 0 项目模块  1：一级模块  2：二级模块
const handleSave = (params) => {
  let apiStr = ''
  // let apiType = 'post'
  if (infoFormType.value == 'add') {
    switch (infoFormLevel.value) {
      case 1:
        apiStr = '/rm2/frontPrjMaint/insertProject'
        break
      case 2:
        apiStr = '/rm2/frontPrjMaint/insertModule1'
        break
      case 3:
        apiStr = '/rm2/frontPrjMaint/insertModule2'
        break
      default:
        apiStr = ''
    }
  } else if (infoFormType.value == 'modify') {
    switch (infoFormLevel.value) {
      case 2:
        apiStr = '/rm2/frontPrjMaint/updateProject'
        // apiType = 'get'
        break
      case 3:
        apiStr = '/rm2/frontPrjMaint/updateModule1'
        break
      case 4:
        apiStr = '/rm2/frontPrjMaint/updateModule2'
        break
      default:
        apiStr = ''
    }
  }

  apiRequestPost(apiStr, params).then((res) => {
    if (res.data.success) {
      infoFormType.value = 'info'
      refreshTreeNode()
      // loadNode(selectedNodeObj.value)
    }
  })
}
const handleDelete = async () => {
  let apiStr = ''
  let params = {}
  if (infoFormType.value == 'info') {
    switch (infoFormLevel.value) {
      case 2:
        apiStr = '/rm2/frontPrjMaint/deleteProject'
        params = { appEname: selectedNode.value?.appEname }
        break
      case 3:
        apiStr = '/rm2/frontPrjMaint/deleteModule1'
        params = { moduleEname1: selectedNode.value?.moduleEname1, appEname: selectedNode.value?.appEname }
        break
      case 4:
        apiStr = '/rm2/frontPrjMaint/deleteModule2'
        params = {
          moduleEname1: selectedNode.value?.moduleEname1,
          moduleEname2: selectedNode.value?.moduleEname2,
        }
        break
      default:
        apiStr = ''
    }
  }
  apiRequestPost(apiStr, params)
    .then((res) => {
      if (res.data.success) {
        refreshTreeNode()
      } else {
      }
    })
    .catch((error: any) => {
      // 处理错误
    })
}
// const currentlySelectedNode = reactive({})
// const refreshTreeNode = () => {
//   console.log(selectedNodeObj, 'selectedNodeObj')
//   useMessage().success('更新成功')
//   let parentId = selectedNodeObj.value?.parent?.id
//   console.log(parentId, 'parentId')
//   let node = treeRef.value.getNode(parentId)
//   console.log(node, 'node')
//   if (node) {
//     setTimeout(() => {
//       node.loaded = false
//       node.expand() // 主动调用展开节点方法，重新查询该节点下的所有子节点
//     }, 1000)
//     // 刷新完成后，重新选中当前节点（如果它仍然存在）
//     const refreshedCurrentNode = treeRef.value.getNode(currentlySelectedNode.id)
//     if (refreshedCurrentNode) {
//       treeRef.value.setCurrentKey(refreshedCurrentNode.key) // 选中当前节点
//     } else {
//       // 如果当前节点不存在（可能已被移除），则尝试选中其父节点
//       treeRef.value.setCurrentKey(node.key) // 选中父节点
//     }
//   }
// }
const refreshTreeNode = () => {
  useMessage().success('更新成功')
  let parentId = selectedNodeObj.value?.parent?.id
  let node = treeRef.value.getNode(parentId)
  console.log(parentId, node)
  if (node) {
    setTimeout(() => {
      node.loaded = false
      // loadNode(selectedNodeObj.value)
      // treeRef.value.expand(selectedNodeObj.value?.parent?.id)
      node.expand() // 主动调用展开节点方法，重新查询该节点下的所有子节点
    }, 1000)
    // 刷新完成后，重新选中当前节点（如果它仍然存在）
    // const refreshedCurrentNode = treeRef.value.getNode(currentlySelectedNode.id)
    // if (refreshedCurrentNode) {
    //   treeRef.value.setCurrentKey(refreshedCurrentNode.key) // 选中当前节点
    // } else {
    //   // 如果当前节点不存在（可能已被移除），则尝试选中其父节点
    //   treeRef.value.setCurrentKey(node.key) // 选中父节点
    // }
  }
}
onMounted(() => {
  // getTreeData('0', {})
  getAllModule1Data()
})
</script>
<style lang="less" scoped>
.page-controller {
  width: 100%;
  display: flex;
  .page-tree {
    // width: 228px;
    width: 280px;
    min-height: calc(100vh - 175px);
    padding: 16px;
    .page-tree__title {
      font-size: 16px;
      color: #303133;
      line-height: 28px;
      text-align: left;
      font-weight: bold;
    }
    .page-tree__line {
      margin: 16px -16px;
      height: 1px;
      background: #e8e8e8;
      width: calc(100% + 32px);
    }
    .page-tree__search {
      margin-bottom: 18px;
    }
    .custom-tree-node {
      display: flex;
      align-items: center;
      justify-content: space-between;
      // width: 100%;
      width: calc(100% - 26px);
      height: 32px;
      padding-right: 5px;
      position: relative;
      &-label {
        width: calc(100% - 20px);
        // width: 100%;
        text-align: left;
        // padding-right: 60px;
      }
      // &-label3 {
      //   width: calc(100% - 50px);
      //   // width: 100%;
      //   text-align: left;
      //   // padding-right: 60px;
      // }
      // &-label4 {
      //   width: calc(100% - 70px);
      //   // width: 100%;
      //   text-align: left;
      //   // padding-right: 60px;
      // }
      &-add {
        position: absolute;
        right: 5px;
        top: 8px;
        color: var(--el-color-primary-light-2);
      }
    }
    .custom-tree-node3 {
      width: calc(100% - 30px);
    }
    .custom-tree-node4 {
      width: calc(100% - 30px);
    }
    ::v-deep(.el-tree-node__content) {
      height: 32px;
      border-radius: 2px;
      .el-tree-node__expand-icon {
        color: #989898;
      }
    }
  }
  .page-form {
    flex: 1;
    margin: 0 20px;
  }
}
::v-deep(.el-dropdown-menu__item) {
  padding: 5px 16px;
  border-radius: 2px;
  margin: 4px;
}
</style>
